package cn.lili.controller.promotion;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.promotion.entity.dos.Coupon;
import cn.lili.modules.promotion.entity.dos.MemberCoupon;
import cn.lili.modules.promotion.entity.dto.search.CouponSearchParams;
import cn.lili.modules.promotion.entity.dto.search.MemberCouponSearchParams;
import cn.lili.modules.promotion.entity.vos.CouponVO;
import cn.lili.modules.promotion.entity.vos.MemberCouponVO;
import cn.lili.modules.promotion.service.CouponService;
import cn.lili.modules.promotion.service.MemberCouponService;
import cn.lili.modules.promotion.service.ReturnActivityUserService;
import cn.lili.modules.promotion.tools.PromotionTools;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 优惠券接口
 *
 * @author paulG
 * @since 2020/10/9
 **/
@RestController
@Api(tags = "优惠券接口")
@RequestMapping("/promotion/coupon")
@RequiredArgsConstructor
public class CouponController {

    private final CouponService couponService;

    private final MemberCouponService memberCouponService;

    private final ReturnActivityUserService returnActivityUserService;

    @ApiOperation(value = "获取优惠券列表")
    @GetMapping
    public ResultMessage<Page<CouponVO>> getCouponList(CouponSearchParams queryParam, PageVO page) {
        AuthUser currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            return ResultUtil.data(couponService.canReceiveCoupon(currentUser.getExtendId(), queryParam, page));
        }
        return ResultUtil.data(couponService.canReceiveCoupon(null, queryParam, page));
    }

    @ApiOperation(value = "获取优惠券详情")
    @GetMapping("/{couponId}")
    public ResultMessage<CouponVO> getCoupon(@PathVariable String couponId) {
        CouponVO coupon = couponService.getDetail(couponId);
        return ResultUtil.data(coupon);
    }

    @ApiOperation(value = "添加优惠券")
    @PostMapping
    public ResultMessage<CouponVO> addCoupon(@RequestBody CouponVO couponVO) {
        this.setStoreInfo(couponVO);
        couponService.savePromotions(couponVO);
        return ResultUtil.data(couponVO);
    }

    @ApiOperation(value = "修改优惠券")
    @PutMapping
    public ResultMessage<Coupon> updateCoupon(@RequestBody CouponVO couponVO) {
        this.setStoreInfo(couponVO);
        Coupon coupon = couponService.getById(couponVO.getId());
        couponService.updatePromotions(couponVO);
        return ResultUtil.data(coupon);
    }

    @ApiOperation(value = "修改优惠券状态")
    @PutMapping("/status")
    public ResultMessage<Object> updateCouponStatus(String couponIds, Long startTime, Long endTime) {
        String[] split = couponIds.split(",");
        if (couponService.updateStatus(Arrays.asList(split), startTime, endTime)) {
            return ResultUtil.success();
        }
        throw new ServiceException(ResultCode.COUPON_EDIT_STATUS_ERROR);
    }

    @ApiOperation(value = "批量删除")
    @DeleteMapping(value = "/{ids}")
    public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) {
        couponService.removePromotions(ids);
        return ResultUtil.success();
    }

    @ApiOperation(value = "会员优惠券作废")
    @PutMapping(value = "/member/cancellation/{id}")
    public ResultMessage<Object> cancellation(@PathVariable String id) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        memberCouponService.cancellation(currentUser.getExtendId(), id);
        return ResultUtil.success();
    }

    @ApiOperation(value = "根据优惠券id券分页获取会员领详情")
    @GetMapping(value = "/member/{id}")
    public ResultMessage<Page<MemberCoupon>> getByPage(@PathVariable String id,
                                                       PageVO page) {
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        Page<MemberCoupon> data = memberCouponService.page(PageUtil.initPage(page),
                queryWrapper.eq("coupon_id", id)
        );
        return ResultUtil.data(data);
    }

    @ApiOperation(value = "获取当前会员的优惠券列表")
    @GetMapping("/getCoupons")
    public ResultMessage<Page<MemberCoupon>> getCoupons(MemberCouponSearchParams param, PageVO pageVo) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        param.setMemberId(currentUser.getExtendId());
        return ResultUtil.data(memberCouponService.getMemberCoupons(param, pageVo));
    }

    @ApiOperation(value = "获取当前会员的对于当前商品可使用的优惠券列表")
    @GetMapping("/canUse")
    public ResultMessage<Page<MemberCoupon>> getCouponsByCanUse(MemberCouponSearchParams param, Double totalPrice, PageVO pageVo) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        param.setMemberId(currentUser.getExtendId());
        return ResultUtil.data(memberCouponService.getMemberCouponsByCanUse(param, totalPrice, pageVo));
    }

    @ApiOperation(value = "会员领取优惠券")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponId", value = "优惠券ID", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping("/receive/{couponId}")
    public ResultMessage<Object> receiveCoupon(@NotNull(message = "优惠券ID不能为空") @PathVariable("couponId") String couponId) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        memberCouponService.receiveBuyerCoupon(couponId, currentUser.getExtendId(), currentUser.getUsername());
        return ResultUtil.success();
    }

    @ApiOperation(value = "获取当前会员可使用的优惠券数量")
    @GetMapping("/getCouponsNum")
    public ResultMessage<Object> getMemberCouponsNum() {
        long memberCouponsCount = memberCouponService.getMemberCouponsNum();
        long userReturnActivityCount = returnActivityUserService.getUserReturnActivityNum();
        return ResultUtil.data(memberCouponsCount + userReturnActivityCount);
    }

    @ApiOperation(value = "获取优惠券领取详情")
    @GetMapping(value = "/received")
    public ResultMessage<Page<MemberCouponVO>> getReceiveByPage(MemberCouponSearchParams searchParams,
                                                                PageVO page) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        if (SceneEnums.STORE.equals(currentUser.getScene()) || SceneEnums.SUPPLIER.equals(currentUser.getScene())) {
            searchParams.setExtendId(currentUser.getExtendId());
        }
        Page<MemberCouponVO> result = memberCouponService.getMemberCouponsPage(PageUtil.initPage(page), searchParams);
        return ResultUtil.data(result);
    }

    private void setStoreInfo(CouponVO couponVO) {

        AuthUser currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        if (SceneEnums.MANAGER.equals(currentUser.getScene())) {
            couponVO.setStoreId(PromotionTools.PLATFORM_ID);
            couponVO.setStoreName(PromotionTools.PLATFORM_NAME);
        } else {
            //如果非平台，无法创建店铺承担部分比例的优惠券
            couponVO.setStoreCommission(100);
            couponVO.setStoreId(currentUser.getExtendId());
            couponVO.setStoreName(currentUser.getExtendName());
        }
    }

    @ApiOperation(value = "获取年会优惠券列表")
    @GetMapping(value = "/getAnnualMeetingCouponList")
    public ResultMessage<List<Coupon>> getAnnualMeetingCouponList () {
        AuthUser currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new ServiceException("您还未登录或登录已过期，请重新登录");
        }
        return ResultUtil.data(couponService.getAnnualMeetingCouponList());
    }
}
